const Base = require('./base.js');
const moment = require('moment');

module.exports = class extends Base {
    /**
     * 提交订单
     * @returns {Promise<*>}
     */
    async submitAction() {
        const d = this.post();
        console.log(d)
		
		const orderId=d[0].order_id;
		
		if(orderId>0){
			
			const order = await this.model('order').field('order_status').where({
            id: orderId
			}).find();

			if (think.isEmpty(order) || order.order_status !== 0) {
				return this.success('此订单不存在');
			}
			
			const order_id = await this.model('order').where({
            id: orderId
			}).update({order_status: -1,is_delete:-1});
		}
        let details = [];
        for (const s of d) {
            const list = await this.model('goods').where({
                id: s.goods_id, is_on_sale: 1
            }).find();
            if (think.isEmpty(list)) {
                return this.fail('此单中商品已被下架，请重新购买');
            }
            details.push({
                goods_id: s.goods_id,
                goods_name: list.goods_name,
                goods_no: list.goods_no,
                primary_pic_url: list.primary_pic_url,
                sale_price: s.price || list.sale_price,
                number: s.number,
                custom_style: s.custom_style,
                is_words: s.is_words,
                words_desc: s.words_desc,
                words_id: s.words_id,
                words_color_id: s.words_color_id,
                status: s.status,
                versionid: s.versionid,
                sizeid: s.sizeid,
                size_list: s.size_list,
				peiliao_list:s.peiliao_list,
				cateid:s.category_id,
				list_data:s.list_data,
				volume_listNew:s.volume_listNew
            });
        }
        let userid = think.user.user_id;
        
        const user_type = await this.model('user').where({id: think.user.user_id}).getField('user_type', true);
        if (user_type === 1) {
            //userid = await this.model('user').where({phone: d[0].phone}).getField('id', true);
        }
        userid = await this.model('user').where({phone: d[0].phone}).getField('id', true);
        
        //return this.success(userid);
        const peiliaoArr=JSON.parse(details[0].peiliao_list);
        //return this.success(peiliaoArr[0].custom_value);
        
        let materialid=await this.model('material').where({mater: peiliaoArr[0].custom_value}).getField('materialid', true);
        let gradeid=await this.model('margrade').where({materailid: materialid,classid:details[0].cateid}).getField('gradeid', true);
        let price=await this.model('proprice').where({proid: details[0].goods_id,gradeid:gradeid}).getField('price', true);
        // 统计商品总价
        let goodsTotalPrice = 0.00;
        let goodsTotalPrice1 = 0.00;
        for (const cartItem of details) {
            goodsTotalPrice += cartItem.number * cartItem.sale_price;//产品标签价格
            goodsTotalPrice1 += cartItem.number * price;//档次价格
        }
        // 获取订单使用的优惠券
        const couponPrice = 0.00;
        // 订单价格计算
        const orderTotalPrice = goodsTotalPrice1 - couponPrice; // 订单的总价
        const orderInfo = {
            order_no: 'SO'+moment().format('YYYYMMDD') + Math.random().toString().substr(2, 5),
            user_id: userid,
            goods_price: goodsTotalPrice,
            order_price: orderTotalPrice,
            //优惠券抵扣
            coupon_id: 0,
            coupon_price: couponPrice,
            parterid: think.user.user_id
        };
        const order_id = await this.model('order').orderadd(orderInfo, details);
        orderInfo.id = order_id;
        return this.success(orderInfo);
    }

    /**
     * 订单详情
     * @returns {Promise<void>}
     */
    async detailsAction() {
        const result = await this.model('order').where({id: this.post('order_id')}).find();
        return this.success(result);
    }

/**
     * 订单状态
     * @returns {Promise<void>}
     */
    async orderStatusAction() {
		let d = this.post();
        const result = await this.model('order').field('order_status').where({
            id: d.order_id
        }).find();
        return this.success(result);
    }

    /**
     * 订单地址编辑
     * @returns {Promise<void>}
     */
    async addressAction() {
        const d = this.post();
        const result = await this.model('order').where({id: d.order_id}).update({
            address_id: d.address_id,
            username: d.username,
            address: d.address,
            phone: d.phone
        });
        return this.success(result);
    }

    /**
     * 获取订单列表
     * @return {Promise}
     */
    async listAction() {
        const d = this.post();
        let whs = {
            _complex: {
                user_id: think.user.user_id,
                parterid: think.user.user_id,
                _logic: 'or'
            }, is_delete: 0, order_status: ['IN', '0,1,2,3,4']
        };
        if (d.order_status !== 'all') {
            whs.order_status = d.order_status;
        }
        const orderList = await this.model('order').where(whs).page(d.page || 1, d.limit || 20).order('add_time desc').countSelect();
        return this.success(orderList);
    }

    /**
     * 取消订单
     * @returns {Promise<void>}
     */
    async cancelAction() {
        let d = this.post();
        const order = await this.model('order').field('order_status').where({
            id: d.order_id
        }).find();

        if (think.isEmpty(order) || order.order_status !== 0) {
            return this.success('此订单不存在');
        }
        const order_id = await this.model('order').where({
            id: d.order_id
        }).update({order_status: -1});
        return this.success(order_id);
    }

    /**
     * 订单数据统计
     * @returns {Promise<void>}
     */
    async countAction() {
        //待付款
        const WaitPay = await this.model('order').where({
            _complex: {
                user_id: think.user.user_id,
                parterid: think.user.user_id,
                _logic: 'or'
            }, order_status: 0, is_delete: 0
        }).count();
        //待发货
        const WaitGoods = await this.model('order').where({
            _complex: {
                user_id: think.user.user_id,
                parterid: think.user.user_id,
                _logic: 'or'
            }, order_status: 1, is_delete: 0
        }).count();
        //待签收
        const WaitReceipt = await this.model('order').where({
            _complex: {
                user_id: think.user.user_id,
                parterid: think.user.user_id,
                _logic: 'or'
            }, order_status: 2, is_delete: 0
        }).count();
        return this.success({
            WaitPay: WaitPay,
            WaitGoods: WaitGoods,
            WaitReceipt: WaitReceipt,
            text: 'WaitPay:待付款，WaitGoods:待发货，WaitReceipt:待签收'
        });
    }

    /**
     * 售后处理订单
     * @returns {Promise<void>}
     */
    async afterSaleAction() {
        const d = this.post();
        const result = await this.model('order').where({
            user_id: think.user.user_id,
            pay_status: 1,
            is_delete: 0
        }).page(d.page || 1, d.limit || 30).order('add_time desc').countSelect();
        return this.success(result);
    }

    /**
     * 售后服务添加
     * @returns {Promise<void>}
     */
    async afterSaleAddAction() {
        const d = this.post();
        const result = await this.model('order_aftersale').add({
            user_id: think.user.user_id,
            order_id: d.order_id,
            order_no: d.order_no,
            parterid: d.parterid,
            after_no: '4300' + moment().format('YYYYMMDD') + Math.random().toString().substr(2, 5),
            username: d.username,
            phone: d.phone,
            reason: d.reason,
            desc: d.desc,
            img: d.img,
            deal_type: d.deal_type,
            deal_status: 0
        });
        return this.success(result);
    }

    /**
     * 售后服务申请列表
     * @returns {Promise<void>}
     */
    async afterSaleListAction() {
        const d = this.post();
        const result = await this.model('order_aftersale').where({
            user_id: think.user.user_id,
            deal_status: ['IN', d.deal_status]
        }).page(d.page || 1, d.limit || 30).order('add_time desc').countSelect();
        return this.success(result);
    }
};
